(function () {
	
	//添加菜单，弹出弹窗
    jQuery('.addBtn').on('click', function () {
    		jQuery('#id').val('');
    		jQuery('#name').val('');
        jQuery('#describe').val('');
        jQuery('#Modal').modal('show');
    });

    //table数据显示
    
	//网格
	var serverDataGrid = {};
	serverDataGrid.divisionId = "0";
	serverDataGrid.key = "";
    var	serverTableGrid;
    
    
    var serverData2 = {};
    serverData2.beginDate = '';
    serverData2.endDate = '';
    serverData2.cyc = 'week';
    serverData2.uId = '';
    serverData2.dataType = '';
	serverData2.dataId = '';
	var	serverTable2;
    
    
    var funnel;
    var funnelData = [];
    var funnelIndex = 0;
    
    var gradingId = '';
    var gridId = '';
    
    var userBar;
    var userBarData = {};
    var userBarIndex = 0;
    var userId = '';
    var cyc = 'week';
    var beginDate = '';
    var endDate = '';
    
    function viewDetails(o){
		window.location = window.rootPath + '/ui/eventRegister?eventReportIdentify='+o.registerEventToReportEvent.id+"&eventRegisterIdentify="+o.id;
    };
    
    jQuery(document).ready(function () {
    		//网格列表
		serverTableGrid = jQuery('#dataTableGrid').DataTable({
            "serverSide": true,
            "ordering": false,
            "ajax": {
                "dataType": "json",
                "type": "post",
                "cache": false,
                "url": window.rootPath+'/ui/TowerAnalysis/getGridAreaPage',
                "data": function (d) {
                    return $.extend({}, d, serverDataGrid);
                }
            },
            columns: [
	        		{
		            data: null,
		            defaultContent: ""
	        		},
	            {
	        			data: 'gridName'
	            },
	            {
	            		data: 'division.divisionName'
	            },
	            {
	            		data: 'gridArea'
	            },
	            {
	            		data: 'typeOpt.title'
	            },
	            {
	            		data: 'gridState.title'
	            }],
            "drawCallback": function ( oSettings ) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for ( var i=oSettings._iDisplayStart, iLen=total ; i<iLen ; i++ )
                {
                    $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[k] ].nTr ).text( i+1 );
                    k++;
                }
                
                gridId = '';
                
                serverTableGrid.off('click','tr');
                serverTableGrid.on( 'click', 'tr', function (event) {
                    event=event||window.event;
                    var target=event.target||event.scrElement;
                    var data = serverTableGrid.row( this ).data();

	            	    if($(this).hasClass('selected') ){
	            			$(this).removeClass('selected');
	            			gridId = '';
	            		}else{
	            	    		serverTableGrid.$('tr.selected').removeClass('selected');
	            	    		$(this).addClass('selected');
	            	    		gridId = data.id;
	            	    }
	            	    setGrading();
	            	    cleanUser();
	            	    cleanPie();
                    return;
                } );
            }
        });
		
		serverTable2 = jQuery('#dataTable2').DataTable({
	        	"serverSide": true,
	        	"ordering": false,
	        	"ajax": {
	        		"dataType": "json",
	        		"type": "post",
	        		"cache": false,
	        		"url": window.rootPath+'/ui/TowerAnalysis/getEvaluatePage',
	        		"data": function (d) {
	        			return $.extend({}, d, serverData2);
	        		}
	        	},
	        	columns: [{
		        		data: null,
		        		defaultContent: ""
		        	},
		        	{
		            data: null,
		            defaultContent: "",
		            render: function (data, type, full, meta) {
		            		var operate ='<button type="button" class="btn btn-sm btn-info detailBtn" title="详情"><i class="fa fa-edit"></i></button>';
		            		return operate;
		            }
		        	},
		        	{
		        		data: 'registerEvent.registerEventName'
		        	},
		        	{
		        		data: 'registerEvent.registerEventType.eventName'
		        	},
		        	{
		        		data: 'registerEvent.registerEventReportTime',
		            render: function (data, type, full, meta) {
		                if (data)
		                    return moment(data).format('YYYY/MM/DD HH:mm');
		                else
		                    return '';
		            }
		        	},
		        	{
		        		data: 'registerEvent.registerEventHierarchy.groupName'
		        	},
		        	{
		        		data: 'registerEvent.registerEventToNetGrid.gridName'
		        	},
		        	{
		        		data: 'registerEvent.registerEventToNetGrid.division.divisionName'
		        	},
		        	{
		        		data: 'registerEvent.registerEventToPartBaseInfo.partName'
		        	},
		        	{
		        		data: 'registerEventEvaluateLevel.gradingName'
		        	},
		        	{
		        		data: 'scale'
		        	}],
	        	"drawCallback": function ( oSettings ) {
	        		var k = 0;
	        		var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;
	        		
	        		for ( var i=oSettings._iDisplayStart, iLen=total ; i<iLen ; i++ )
	        		{
	        			$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[k] ].nTr ).text( i+1 );
	        			k++;
	        		}
	        		
	        		serverTable2.off('click','tr');
	        		serverTable2.on( 'click', 'tr', function (event) {
	        			event=event||window.event;
	        			var target=event.target||event.scrElement;
	        			var data = serverTable2.row( this ).data();
	        			if (target.className.indexOf('fa-edit') != -1 ||target.className.indexOf('detailBtn') != -1) {
	        				viewDetails(data.registerEvent);
	        			}
	        			return;
	        		} );
	        	}
	    });
    
	    //详情查询
	    jQuery('.searchBtn2').on('click',function(){
	        	serverData2.key=jQuery('#search2').val();
	        	serverTable2.draw();
	    })
	    
	    //详情撤销查询
	    jQuery('.resetBtn2').on("click",function(){
	        	jQuery('#search2').val('');
	        	serverData2.key ='';
	        	serverTable2.draw();
	    });
        
        //查询
        jQuery('.searchBtnGrid').on('click',function(){
            serverDataGrid.key=jQuery('#searchGrid').val();
            serverTableGrid.draw();
        })
        
        //撤销查询
        jQuery('.resetBtnGrid').on("click",function(){
            jQuery('#searchGrid').val('');
            serverDataGrid.key ='';
            serverTableGrid.draw();
        });
        
        //周期切换
        jQuery('#cyc').on('change',function(){
        		cyc = $(this).val();
        		serverData2.cyc = cyc;
        		var cycDate = $('#cycDate');
        		if(cyc == 'custom'){
        			cycDate.show();
        		}else{
        			cycDate.hide();
        			getUserData();
        		}
        });
        
        jQuery('.cycBtn').on("click",function(){
	    		beginDate = $('#beginDate').val();
	    		endDate = $('#endDate').val();
	    		
	    	    serverData2.beginDate = beginDate;
	    	    serverData2.endDate = endDate;
	    	    
	    		if(beginDate == '' || endDate == ''){
	    			alert("请选择周期时间");
	    			return;
	    		}
	    	    getUserData();
        });
        
        funnel.on('click', function (params) {
        		gradingId = params.data.id;
	    		showDownplay(funnelIndex);
	    		funnelIndex = params.dataIndex;
	    		showHighlight(funnelIndex);
	    		getUserData();
	    		cleanPie();
        });

        userBar.on('click', function (params) {
	        	userId = params.data.id;
	        	userBarIndex = params.dataIndex;
	        	serverData2.uId = userId;
	        	getAnalysisData(userId);
	        	serverTable2.draw(false);
        });
        
        //部件监听
        pie1.on('click', function (params) {
    			serverData2.dataType = params.seriesName;
    			serverData2.dataId = params.data.id;
    			serverTable2.draw(false);
        });
        
        //事件监听
        pie2.on('click', function (params) {
	        	serverData2.dataType = params.seriesName;
	        	serverData2.dataId = params.data.id;
	        	serverTable2.draw(false);
        });
        
    });
    
  	/********************* funnel *******************/
    funnel = echarts.init(document.getElementById('funnel'));
    
    var option = {
        tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b}"
        },
        calculable: false,
        series: [{
            name: '评分层级',
            type: 'funnel',
            left: '1%',
            bottom: '5%',
            //x2: 80,

            width: '98%',
            min: 0,
            max: 1,
            minSize: '0%',
            maxSize: '100%',
            sort: 'ascending',//ascending descending
            gap: 2,
            label: {
                normal: {
                    show: true,
                    position: 'inside'
                },
                emphasis: {
                    textStyle: {
                        fontSize: 18
                    }
                }
            },
            labelLine: {
                normal: {
                    length: 10,
                    lineStyle: {
                        width: 1,
                        type: 'solid'
                    }
                }
            },
            itemStyle: {
                normal: {//正常情况显示
                    borderColor: '#fff',
                    borderWidth: 1
                },
            emphasis:{//高亮情况显示
                borderColor: '#f00',
                borderWidth: 4,
                }
            },
            data: ''

        }]
    };
    
    funnel.setOption(option);
    
    function showDownplay(index){
	    // 取消之前高亮的图形
	    funnel.dispatchAction({
	        type: 'downplay',
	        seriesIndex: 0,
	        dataIndex: index
	    });
    }
    
    function showHighlight(index){
	    // 高亮当前图形
	    funnel.dispatchAction({
	        type: 'highlight',
	        seriesIndex: 0,
	        dataIndex: index
	    });
    }
    
    //评分层级数据
    function setGrading(){
    	
    		funnelData = [];
		updateFunnel(funnelData);
    		if(gridId == ''){
    			return;
    		}else{
    			var url=window.rootPath+'/ui/griduser/getGrading/'+gridId;
            jQuery.ajax({
            		url:encodeURI(url),
        			type:'post',
        			data:'',
        			dataType:'json',
        			contentType:'application/json;charset=utf-8',
        			success: function (data) {
        				var gradings = data.gradings;
        				if(gradings.length > 0){
	        				for(var i=0;i<gradings.length;i++){
	                			var item = {};
	                    		item.name = gradings[i].gradingName;
	                    		item.value = gradings[i].gradingLevel.extended1;
	                    		item.id = gradings[i].id;
	                    		funnelData.push(item);
	        				}
        				}else{
        					funnelData = [];
        				}
        				bubbleSort(funnelData);
        				var data = reSetSortNum(funnelData);
        				updateFunnel(data);
        			}
            });
    		}
    }
    
    //冒泡排序
    function bubbleSort(arr) {
        var len = arr.length;
        for (var i = 0; i < len; i++) {
            for (var j = 0; j < len - 1 - i; j++) {
                if (arr[j].value > arr[j+1].value) {        //相邻元素两两对比
                    var temp = arr[j+1];        //元素交换
                    arr[j+1] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        return arr;
    }
    
    //重新设置排序号
    function reSetSortNum(arr){
    		var newObject = jQuery.extend(true, [], arr);
    		var len = newObject.length;
    		for(var i=0;i<len;i++){
    			newObject[i].value = i+1;
    		}
    		return newObject;
    }
    
    //更新数据
    function updateFunnel(data){
	    	funnel.setOption({
	    		series:{
	    			max:data.length,
	    			data :data
	    		}
	    	});
    }
    
    /******************** userBar **************************/
    
    userBar = echarts.init(document.getElementById('userBar'));
    
    var userBarOption = {
    		dataZoom: {
    		    show: false,
    		    realtime: true,
    		    start: 0,
    		    end: 100
    		},
    	    tooltip : {
    	        trigger: 'axis'
    	    },
    	    legend: {
    	        data:[]
    	    },
    	    grid: {
    	    		y2: 140
    	    },
    	    xAxis :{
    	    		type : 'category',
    	    		data : [],
    	    		splitLine:{show: false},//去除网格线
    	    		axisLabel:{
    	    			interval : 0,
    	    			rotate : -30,
    	    		}
	    },
    	    yAxis : {
    	    		type : 'value'
    	    },
    	    series : [
    	        {
    	        		name:'人员',
    	            type:'bar',
    	            data:[],
    	            itemStyle: {
    	            		normal: {
    	            			label: {
    	            				show: true,
    	            				position: 'top',
    	            				formatter: '{c}'
    	            			}
    	            		}
    	            }
    	        }
    	    ]
    	}; 
    
    userBar.setOption(userBarOption);
    
    //更新数据
    function updateUserBar(data){
    		userBar.setOption({
    			dataZoom:data.dataZoom,
	    		series:{
	    			data :data.series
	    		},
	    		xAxis:{
	    			data :data.xAxis
	    		}
	    	});
    }
    
    //获取人员信息
    function getUserData(){
    		userBarData.series = [];
    		userBarData.xAxis = [];
    		var dataZoom = {
    		    show: false,
    		    start: 0,
    		    end: 100
    		};
    		userBarData.dataZoom = dataZoom;
    		updateUserBar(userBarData);
    		if(gridId == '' || gradingId == ''){
    			return;
    		}else{
        		var d = {
        			'cyc' : cyc,
        			'beginDate' : beginDate,
        			'endDate' : endDate
        		};
    			var url=window.rootPath+'/ui/TowerAnalysis/getUser/'+gridId+'/'+gradingId;
            jQuery.ajax({
            		url:encodeURI(url),
        			type:'post',
        			data:JSON.stringify(d),
        			dataType:'json',
        			contentType:'application/json;charset=utf-8',
        			success: function (data) {
        				var users = data.users;
        				var len = users.length;
        				var series = [];
        				var xAxis = [];
        				if(len > 0){
        					if(len>10){
        						dataZoom.show = true;
        						var size = parseInt(1000 /len);
        						dataZoom.end = size;
        					}
        					series = users;
	        				for(var i=0;i<len;i++){
	        					xAxis.push(users[i].name);
	        				}
        				}
    	    				userBarData.series = series;
    	    				userBarData.xAxis = xAxis;
    	    				userBarData.dataZoom = dataZoom;
    	    				updateUserBar(userBarData);
        			}
            });
    		}
    }
    
    //获取分析数据
    function getAnalysisData(id){
		var d = {
    			'cyc' : cyc,
    			'beginDate' : beginDate,
    			'endDate' : endDate
    		};
	    jQuery.ajax({
	        url:window.rootPath+'/ui/ScoreAnalysis/getAnalysisData/'+id,
	        cache:false,
	        type :"post",
	        data :JSON.stringify(d),
	        dataType:"json",
	        contentType:'application/json;charset=utf-8',//解决返回数据中的中文乱码问题
	        success:function(data){
	        		var part = data.part;
	        		updatePieForPart(part);
	        		var event = data.event;
	        		updatePie(event);
	        		var grid = data.grid;
	        }
	    });
	};
    /******************* 按部件进行分类 ***************************/
    var pie1;
    pie1 = echarts.init(document.getElementById('pie1'));
    var option1 = {
    	    title: {
    	        text: '部件',
    	        x: 'center',
    	        y: 'center',
    	        textStyle: {
    	            fontWeight: 'normal',
    	            fontSize: 22
    	        }
    	    },
    	    tooltip: {
    	        trigger: 'item',
    	        formatter: function(params, ticket, callback) {
    	        		var part = '';
    	        		if(params.name == "非部件"){
    	        			part = '非部件';
    	        		}else{
    	        			part = '部件';
    	        		}
    	            var res = part +'</br>' 
    	            		+ params.name + ' : ' + params.value + '</br>' 
    	            		+ params.percent +'%';
    	            return res;
    	        }
    	    },
    	    legend: {
    	        orient: 'horizontal',
    	        x: 'center',
    	        y: 'top',
    	        right: '0%',
    	        bottom: '0%',
    	        data: '',
    	        itemWidth: 40,
    	        itemHeight: 30
    	    },
    	    series: [
    	    	 {
    	             name:'part',
    	             type:'pie',
    	             selectedMode: 'single',
    	             radius: [0, '45%'],
    	             label: {
    	                 normal: {
    	                     position: 'inner'
    	                 }
    	             },
    	             labelLine: {
    	                 normal: {
    	                     show: false
    	                 }
    	             },
    	             data:''
    	         },
    	         {
    	             name:'part',
    	             type:'pie',
    	             radius: ['55%', '90%'],
				 label: {
					normal: {
						position: 'inner',
						textStyle: {
							color: '#fff',
							fontSize: 14
						}
					}
				 },
				 labelLine: {
					normal: {
						show: false
					}
				 },
    	             data:''
    	         }
    	    ]
    	};
    pie1.setOption(option1);
    
    function updatePieForPart(data){
    		pie1.setOption({
	    	//	legend:{ data : data.legend },
	    		series:[{ data : data.seriesIn },{data : data.seriesOut}]
	    	});
	}
 	/******************* 按事件进行分类 ***************************/
    var pie2;
    pie2 = echarts.init(document.getElementById('pie2'));
    var option2 = {
    		title: {
    			text: '事件类型',
    			x: 'center',
    			y: 'center',
    			textStyle: {
    				fontWeight: 'normal',
    				fontSize: 22
    			}
    		},
    		tooltip: {
    			trigger: 'item',
    			formatter: function(params, ticket, callback) {
    				var res =  params.name + ' : ' + params.value + '<br>' 
    				+ params.percent +'%';
    				return res;
    			}
    		},
    		legend: {
    			orient: 'horizontal',
    			x: 'center',
    			y: 'top',
    			right: '0%',
    			bottom: '0%',
    			data: '',
    			itemWidth: 40,
    			itemHeight: 30
    		},
    		series: [{
    			name: 'event',
    			type: 'pie',
    			selectedMode: 'single',
    			radius: ['50%', '90%'],
    			label: {
    				normal: {
    					position: 'inner',
    					textStyle: {
    						color: '#fff',
    						fontSize: 14
    					}
    				}
    			},
    			labelLine: {
    				normal: {
    					show: false
    				}
    			},
    			data: ''
    		}]
    };
    pie2.setOption(option2);
    
    function updatePie(data){
    		pie2.setOption({
    			series:{ data : data.series }
		});
    }
    
    /**********************************************/
    
    ////////////////初始化模型的树结构/////////////////////////
    var modalSetting = {
        edit:{
            enable: false,
            showRemoveBtn:false,
            showRenameBtn:false,
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "parentId",
                rootParentId: 0
            }
        },
        view:{
            showLine:true
        },
        check: {
			enable: false,
			chkStyle: "radio",
			radioType: "level"
		},
        callback:{
            onClick:getDivsionGridAreaInfo
        }

    };
    
    //获取当前区域的网格信息
    function getDivsionGridAreaInfo(e, treeId, treeNode){
    		var Id=treeNode.id;
		//if('0' == Id) return;
    		serverDataGrid.divisionId = Id;
    		serverTableGrid.draw(false);
    	    
    		//清空数据
    		gridId = '';
    		//塔型
    		cleanFunnel();
    		//用户
    		cleanUser();
    		//数据分析
    		cleanPie();
        	
    }
    
    function cleanFunnel(){
    		funnelIndex = 0;
		gradingId = '';
		funnelData = [];
		updateFunnel(funnelData);
    };
    
    function cleanUser(){
		userBarIndex = 0;
		userBarData.series = [];
		userBarData.xAxis = [];
		var dataZoom = {
		    show: false,
		    start: 0,
		    end: 100
		};
		userBarData.dataZoom = dataZoom;
		updateUserBar(userBarData);
    }
    
    function cleanPie(){
		var dataPie1 = {};
		dataPie1.seriesIn = [];
		dataPie1.seriesOut = [];
		updatePieForPart(dataPie1);
		var dataPie2 = {};
		dataPie2.series = [];
	    updatePie(dataPie2);
	    
	    //详情
		serverData2.dataType = '';
	    	serverData2.dataId = '';
	    	serverData2.uId = '';
	    	serverTable2.draw(false);
    }
    
    //初始化 层级树
    var primaryNode=[];
    var url = window.rootPath +'/ui/TowerAnalysis/getAllNodes';
    jQuery.ajax({
        url:url,
        cache:false,
        type :"get",
        data:'',
        dataType:"json",
        contentType:'application/json;charset=utf-8',//解决返回数据中的中文乱码问题
        success:function(data){
            primaryNode.push(
                {
                    id: 0,
                    name: "区域层级",
                    open: "true",
                    icon: "/wcsi/img/defaultDivision.png"
                }
            );
            for (var i = 0; i < data.nodes.length; i++) {
                primaryNode.push(data.nodes[i]);
            }
            $.fn.zTree.init($("#hierarchyTree"),modalSetting,primaryNode);
        }
    });

})();